package com.reeygu.item.config;

import com.reeygu.item.pojo.User;
import com.reeygu.item.service.UserService;
import com.reeygu.item.utils.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 参数解析器
 */
@Slf4j
@Component
public class UserArgumentResolvers implements HandlerMethodArgumentResolver {

    @Autowired
    private UserService userService;

    //判断是否含有User参数，有则拦截
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType() == User.class;
    }

    //拦截后处理：转换好User对象给业务接口
    @Override
    public User resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) throws Exception {
//        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
//        String userTicket = CookieUtil.getCookieValue(request, "userTicket");
//        log.info("拦截一条需要校验用户身份的信息userTicket:" + userTicket);
//        return userService.getUserInfo(userTicket, request, webRequest.getNativeResponse(HttpServletResponse.class));
        //换成线程存储的方式,获取方法在方法拦截器里面
        return UserContext.getUser();
    }
}
